﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

using cma.cimiss.client;
using cma.cimiss;

using RadarMonitor.DB;

namespace RadarMonitor.CIMISS
{
    public class CIMISSMonitor
    {
        #region 单例
        private static readonly Lazy<CIMISSMonitor>
            lazy =
            new Lazy<CIMISSMonitor>
                (() => new CIMISSMonitor());

        public static CIMISSMonitor Instance { get { return lazy.Value; } }

        private CIMISSMonitor()
        {
           
        }
        #endregion

        // CIMISS 数据正常 事件
        public event Action<string> RadarDataTransmissionSuccessed;
        // CIMISS 数据传输延时报警 事件
        public event Action<DateTime?, string> RadarDataTransmissionTimeoutEvent;
        // CIMISS 访问失败事件 
        public event Action<string> CIMISSAccessFailedEvent;


        // 用户名
        public string UserId { get; set; } = "BEJN_WHQX_BFWE";// 实际测试必须加上这个前缀 BEJN_
        // 密码
        public string UserPwd { get; set; } = "yb2004";

        public string staId { get; set; } = "Z9631";
        // 查询间隔（单位秒）
        public int QueryInterval { get; set; } = 6 * 60;
        // 报警间隔（单位秒）：多久数据没更新触发报警
        public int AlarmInterval { get; set; } = 16 * 60; //测试发现8分钟很容易触发，感觉数据不是实时上传的

        private Timer loopTimer = null;

        public bool Running { get; private set; } = false;

        internal void Start()
        {
            if (loopTimer != null)
                return;
            loopTimer = new Timer(CheckLoop, null, 0, QueryInterval * 1000);
            Running = true;
        }

        internal void Stop()
        {
            loopTimer?.Dispose();
            loopTimer = null;
            Running = false;

        }

        public void CheckLoop(object info)
        {
            DateTime now = DateTime.UtcNow;
            DateTime start = now.AddSeconds(-AlarmInterval);  
            var timeRange = $@"[{start.ToString("yyyyMMddHHmmss")},{now.ToString("yyyyMMddHHmmss")}]";


            /* 1. 定义client对象 */
            DataQueryClient client = new DataQueryClient();

            /* 2.调用方法的参数定义，并赋值 */
            /*   2.1 用户名&密码 */
            /*   2.2 接口ID */
            String interfaceId = "getRadaFileByTimeRangeAndStaId";
            /*   2.3 接口参数，多个参数间无顺序 */
            Dictionary<String, String> params1 = new Dictionary<String, String>();
            // 必选参数 
            params1.Add("dataCode", "RADA_L2_VOSC_ST"); // 资料代码 
            params1.Add("staIds", staId);// 站号
            params1.Add("timeRange", timeRange); // 检索时间范围

            // 可选参数 
            params1.Add("orderby", "Datetime:desc"); // 排序：按照资料时间降序
            params1.Add("limitCnt", "10");

            /* 2.4 返回对象 */
            RetFilesInfo retFilesInfo = new RetFilesInfo();

            /* 3. 调用接口 */
            try
            {
                //初始化接口服务连接资源
                client.initResources();
                //调用接口
                int rst = client.callAPI_to_fileList(UserId, UserPwd, interfaceId, params1, retFilesInfo);
                //输出结果
                if (rst == 0)
                { //正常返回
                    //ClibUtil clibUtil = new ClibUtil();
                    //clibUtil.outputRst(retFilesInfo);
                    fileProcess(retFilesInfo);
                }
                else
                { //异常返回
                    var error = $@"读CIMISS异常({rst})";
                    try
                    {
                        var errorDes = retFilesInfo.request.errorMessage;
                        error += $@" :{errorDes}";
                    }
                    catch { }
                    
                    if (rst == -1)// 查询成功,没有获取到数据（数据库中无数据）
                    {
                        RadarDataTransmissionTimeoutEvent?.Invoke(DateTime.Now, error);
                    }
                    else // 访问CIMISS失败
                    {
                        CIMISSAccessFailedEvent?.Invoke(error);
                    }
                   
                }
            }
            catch (Exception e)
            {
                //异常输出
                Console.WriteLine(e.Message);
            }
            finally
            {
                //释放接口服务连接资源
                client.destroyResources();
            }
        }

        private void fileProcess(RetFilesInfo retFilesInfo)
        {
            if(retFilesInfo.fileInfos !=null && retFilesInfo.fileInfos.Length > 0)
            {
                //RADR_CHN_DOR_L2_O_UF-Z9631-SA-CAP-20210502000405.bz2
                RadarDataTransmissionSuccessed?.Invoke(null);
            }
            else //超时
            {
                RadarDataTransmissionTimeoutEvent?.Invoke(DateTime.Now, null);
            }
        }
    }
}
